<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="单据编号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="billNo"
            >
              <a-input v-model="model.billNo" disabled placeholder="请输入单据编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="审批流程"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="billFlowType"
            >
              <j-dict-select-tag
                type="list"
                :disabled="formDisabled"
                v-model="model.billFlowType"
                dictCode="spare_part_appliction_flow"
                placeholder="请选择审批流程"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="提报人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="applyUser"
            >
              <a-input-search
                v-model="model.applyUserName"
                placeholder="请输入提报人"
                readonly
                enter-button
                @search="handleSelectUser"
                :disabled="formDisabled"
              ></a-input-search>
              <a-input v-model="model.applyUser" hidden></a-input>
            </a-form-model-item>
          </a-col>
          <Tsl-Select-User-Single ref="selectUserModal1" @selectFinished="selectOK"></Tsl-Select-User-Single>

          <!-- <a-col :span="8">
            <a-form-model-item label="订单日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billDate">
              <j-date placeholder="请选择订单日期" v-model="model.billDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>-->
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="制单人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createBy"
            >
              <a-input v-model="model.createBy" placeholder="请输入申请人" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="制单部门"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="sysOrgCode"
            >
              <j-select-depart disabled v-model="model.sysOrgCode" :multi="false" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="制单日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createTime"
            >
              <a-input v-model="model.createTime" disabled></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="明细" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="sparePartApplicationBillDetailTable.loading"
          :columns="sparePartApplicationBillDetailTable.columns"
          :dataSource="sparePartApplicationBillDetailTable.dataSource"
          :maxHeight="300"
          :rowNumber="false"
          :rowSelection="true"
          :toolbar="true"
          :toolbarConfig="{ slot: ['prefix', 'suffix'], btn: [] }"
          rowSelectionType="radio"
          class="bold-border"
          :clickSelectRow="true"
          @cell-click="cellClickEvent"
        >
          <template v-slot:toolbarSuffix>
            <a-button
              type="primary"
              icon="PlusCircleOutlined"
              @click="addMateriel"
              :disabled="formDisabled"
            >新增</a-button>
          </template>

          <template v-slot:action="props">
            <a-popconfirm v-show="!formDisabled" title="确定删除吗？" @confirm="handleDelDetail(props)">
              <a>删除</a>
            </a-popconfirm>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>

    <!-- <erp-goods-supplier-list-modal ref="selectSuppliersList" @supplierOk="supplierOk" @materialId="materialId">
    </erp-goods-supplier-list-modal>-->

    <erp-goods-list-model
      ref="selectGoodsList"
      category="3"
      @goodsDataOk="goodsOk"
      checkval="checkbox"
    ></erp-goods-list-model>

    <erp-supplier-list-modal ref="selectSuppliersList" @supplierOk="supplierOk" checkval="radio"></erp-supplier-list-modal>
  </a-spin>
</template>

<script>
import { getAction, putAction, httpAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import moment from 'dayjs'
import store from '@/store'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import TslSelectUserSingle from '@/components/tsl/TslSelectUserSingle.vue'
import ErpGoodsListModel from '@comp/base/modal/ErpGoodsListModal'
import { array } from 'js-md5'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import { tr } from 'voca'
import ErpSupplierListModal from '@comp/base/modal/ErpSupplierListModal'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'

export default {
  name: 'SparePartApplicationBillForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    JSelectDepart,
    TslSelectUserSingle,
    ErpGoodsListModel,
    ErpSupplierListModal,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        billNo: '',
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        billNo: [{ required: true, message: '请输入单据编号!' }],
        applyUserName: [{ required: true, message: '请选择提报人!' }],
        billFlowType: [{ required: true, message: '请选中审批流程!' }],
      },
      refKeys: ['sparePartApplicationBillDetail'],
      tableKeys: ['sparePartApplicationBillDetail'],
      activeKey: 'sparePartApplicationBillDetail',
      // 五金配件请购单明细
      sparePartApplicationBillDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '序号',
            key: 'seq',
            type: JVXETypes.normal,
            width: '60px',
            defaultValue: '',
          },
          {
            title: '物料编号',
            key: 'materialNo',
            type: JVXETypes.normal,
            width: '150px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '规格',
            key: 'spec',
            type: JVXETypes.normal,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '物料描述',
            key: 'materialDesc',
            type: JVXETypes.input,
            width: '150px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
            disabled: false,
          },
          {
            title: '单位',
            key: 'unit',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '数量',
            key: 'num',
            type: JVXETypes.inputNumber,
            width: '100px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
            disabled: false,
          },
          {
            title: '到货日期',
            key: 'arriveDate',
            type: JVXETypes.date,
            width: '100px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
            disabled: false,
          },
          {
            title: '使用部门',
            key: 'applyDepart',
            type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
            disabled: false,
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            disabled: false,
          },
          {
            title: '供应商编号',
            key: 'supplierNo',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
            visible: false,
            disabled: true,
          },
          {
            title: '供应商名称',
            key: 'supplierName',
            type: JVXETypes.normal,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
            visible: false,
            disabled: true,
          },
          {
            title: '单价',
            key: 'price',
            type: JVXETypes.input,
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
            visible: false,
            disabled: false,
          },
          {
            title: '单价描述',
            key: 'priceDesc',
            type: JVXETypes.input,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
            visible: false,
            disabled: false,
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      url: {
        add: '/procurement/sparePartApplicationBill/add',
        edit: '/procurement/sparePartApplicationBill/edit',
        queryById: '/procurement/sparePartApplicationBill/queryById',
        sparePartApplicationBillDetail: {
          list: '/procurement/sparePartApplicationBill/querySparePartApplicationBillDetailByMainId',
        },
      },
      //是否为审批过程中
      isCommitted: false,
      //是否可以修改供应商及单价
      editSupplier: false,
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    let user = store.getters.userInfo
    if (!this.model.createBy) {
      this.model.createBy = user.username
      this.model.sysOrgCode = user.departIds
    }

    //只有查看详情时显示供应商单价信息
    if (this.disabled) {
      //需要让供应商列显示出来
      if (this.sparePartApplicationBillDetailTable.columns.length > 0) {
        this.sparePartApplicationBillDetailTable.columns.forEach((element) => {
          element.visible = true
          element.disabled = true
        })
      }
    }

    //如果是审批流进来的时候要将审批流的数据显示出来
    if (this.customFormData.id != null) {
      this.model = this.customFormData

      if (this.model.taskName == '王美峰') {
        this.editSupplier = true
        if (this.sparePartApplicationBillDetailTable.columns.length > 0) {
          this.sparePartApplicationBillDetailTable.columns.forEach((element) => {
            element.visible = true
            if (element.key === 'price' || element.key === 'priceDesc') {
              element.disabled = false
            } else {
              element.disabled = true
            }
          })
        }
      }

      //刷新子表数据
      this.editAfter()
    }
  },
  methods: {
    addBefore() {
      this.sparePartApplicationBillDetailTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(
          this.url.sparePartApplicationBillDetail.list,
          params,
          this.sparePartApplicationBillDetailTable
        )
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        sparePartApplicationBillDetailList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    generateBillNo() {
      let url = '/sys/fillRule/executeRuleByCode/spare_part_application_bill'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.billNo = res.result
        }
      })
    },
    add() {
      this.generateBillNo()
    },
    handleSelectUser() {
      this.$refs.selectUserModal1.visible = true
    },
    selectOK(data) {
      this.model.applyUserName = data.employeeName
      this.model.applyUser = data.employeeCode
      this.$forceUpdate()
    },
    addMateriel() {
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
    },
    goodsOk(arr) {
      if (arr.length > 0) {
        arr.forEach((data) => {
          let detailaaa = {}
          detailaaa.materialName = data.name
          detailaaa.materialNo = data.code
          detailaaa.materialId = data.id
          detailaaa.spec = data.noneSpec
          detailaaa.unit = data.meUnit_dictText
          detailaaa.seq = this.sparePartApplicationBillDetailTable.dataSource.length + 1
          this.sparePartApplicationBillDetailTable.dataSource.push(detailaaa)
        })
      }
    },
    handleDelDetail(props) {
      props.target.removeRows(props.row)
      if (this.sparePartApplicationBillDetailTable.dataSource.length > 0) {
        this.sparePartApplicationBillDetailTable.dataSource.splice(
          this.sparePartApplicationBillDetailTable.dataSource.findIndex((d) => d.id === props.row.id),
          1
        )

        this.sparePartApplicationBillDetailTable.dataSource.forEach((element, index) => {
          element.seq = index + 1
        })
      }
    },
    initDictConfig() {},
    cellClickEvent({ row, column }) {
      if (this.editSupplier && (column.property === 'supplierName' || column.property === 'supplierNo')) {
        this.row = row
        this.$refs.selectSuppliersList.add()
        this.$refs.selectSuppliersList.title = '选择供应商'
        this.$refs.selectSuppliersList.disableSubmit = false
      }
    },
    supplierOk(res) {
      this.$set(this.row, 'supplierName', res.name)
      this.$set(this.row, 'supplierNo', res.code)
    },
    //提交表单数据
    request(formData) {
      let url = this.url.add,
        method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true

      httpAction(url, formData, method)
        .then((res) => {
          if (res.success) {
            //241119修改提交时还要判断是否直接进入审批流
            if (!this.model.id) {
              this.model.dataId = res.message
              this.applySubmit(this.model)
            }
            this.$message.success('保存成功')
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }

      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
          return
        } else {
          var params = Object.assign(
            {
              dataId: record.dataId,
            },
            record
          )
          definitionStartByDataId(record.dataId, 'sparePartApplicationBillService', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
              } else {
                this.$message.error(res.message)
              }
            })
            .finally()
        }
      })
    },
  },
}
</script>

<style scoped></style>
